package com.mojito.gorm.bind;

import com.mojito.gorm.map.SqlMapInfo;
import com.mojito.gorm.session.GormSession;
import com.mojito.gorm.session.impl.DefaultGormSession;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @author mojito
 */
@Slf4j
public class GormMapperProxy<T> implements InvocationHandler {
    private static final String LIST_FLAG = "List";
    private Class<T> mapperInterface;
    private GormSession session;


    public GormMapperProxy(Class<T> mapperInterface, GormSession session) {
        this.mapperInterface = mapperInterface;
        this.session = session;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        DefaultGormSession defaultGormSession = (DefaultGormSession) session;
        String key = mapperInterface.getName() + "." + method.getName();
        SqlMapInfo sqlMapInfo = defaultGormSession.getConfiguration().sqlMaps.get(key);
        if (sqlMapInfo == null) {
            throw new NoSuchMethodException("no such method proxy");
        }
        log.info("SQL: {}", sqlMapInfo);
        Object execute = defaultGormSession.getExecutor().execute(sqlMapInfo, args);
        Class<?> returnType = method.getReturnType();
        // TODO: 2020/7/15 目前只支持list和但一类型不支持其他复杂的集合类型
        if (LIST_FLAG.equals(returnType.getSimpleName())) {
            return execute;
        }
        List<T> res = (List<T>) execute;
        if (res.size() == 0) {
            return null;
        }
        return res.remove(0);
    }
}
